<?php
	session_start();
	$message=null;
	$currentWishlistId=null;

	require('config/mysql.config.inc');
	$mysqli = new mysqli($host, $username, $password, $db);	
	
	//grab the user id
	$uid=null;
	if (isset($_SESSION['user'])){
		$username= $mysqli->query("SELECT uid FROM Users WHERE email='".$_SESSION['user']."'");
		$username= $username->fetch_row();
		$uid=$username[0];
	} else {
		$message=$message. "Please log in.";
	}
	
	//A "FUNCTION" TO SEE IF THE CURRENT customid BELONGS TO THE CURRENT LOGGED IN USER
	//keep going if the $id of the wishlist belongs to the currently logged in user
	$keepGoing=false;
	if (isset($_GET['customid'])){
		
		//require('config/mysql.config.inc');
		//$mysqli = new mysqli($host, $username, $password, $db);	
		
		$query="SELECT * FROM Wishlists NATURAL JOIN InWishlist WHERE uid='".$uid."' AND customid='".$_GET['customid']."'";
		$result = $mysqli->query($query);
		//if($result){print "YO";}else{print("FUCK");}
		if ($result->num_rows==1){
			$keepGoing=true;
			$customid=$_GET['customid'];
			$currentWishlistId=$result->fetch_row();
			$currentWishlistId=$currentWishlistId[0];
		} else {
			$message=$message." The item you have selected does not belong to you. ";			
		}
	} else {
		if (!(isset($_GET['modelno']) && isset($_GET['addwishlist']))) {
			//customid not set
			$message=$message." Please go back and choose an item you would like to edit. ";
		}
	}	
	
	
if(isset($_GET['modelno']) && isset($_GET['addwishlist'])){
	$modelno = $_GET['modelno'];

	$result = $mysqli->query("SELECT * FROM Pieces WHERE modelno = '".$modelno."'");

	if($result->num_rows == 0){
		$message=$message." This model number does not exist. ";
	} else {
		$modelData = $result->fetch_assoc();
		
		//get the wishlist id when given the idname
		$query= "SELECT wishlistid FROM Wishlists WHERE wname='".$_GET['addwishlist']."' AND uid='".$uid."'";
		$temp= $mysqli->query($query);
		$temp= $temp->fetch_row();
		$wishlistid = $temp[0];

		if ($wishlistid==0) {
			$message=" This is not your wishlist. You cannot add to it. ";
		} else {
			$currentWishlistId=$wishlistid;
			//CHECK TO SEE IF THIS EXACT PIECE WITH THIS EXACT CONFIG ALREADY EXISTS AND UPDATE QUANTITY	
			$query="SELECT * FROM InWishlist NATURAL JOIN CustomPieces WHERE wishlistid='".$wishlistid."' AND modelno='".$modelno."'";
			$thisModel= $mysqli->query($query);
			
			$exactMatchId=-1;
			while ($customPiece = $thisModel->fetch_assoc()) {
				//see if any $customPiece (a custom piece) matches $modelData's data exactly
				//if it does, set $exactMatchId to the id of the matching piece
				$exact=true;
				
				if ($customPiece['categoryid'] != $modelData['categoryid'])	{	$exact=false;	}
				if ($customPiece['typeid'] != $modelData['typeid'])			{	$exact=false;	}
				if ($customPiece['finishid'] != $modelData['finishid'])		{	$exact=false;	}	
				if ($customPiece['materialid'] != $modelData['materialid'])	{	$exact=false;	}
				if ($customPiece['shapeid'] != $modelData['shapeid'])		{	$exact=false;	}
				if ($customPiece['length'] != $modelData['length'])			{	$exact=false;	}
				if ($customPiece['width'] != $modelData['width'])			{	$exact=false;	}
				if ($customPiece['height'] != $modelData['height'])			{	$exact=false;	}

				//did all of those tests pass?
				if ($exact) {
					$exactMatchId=$customPiece['customid'];
				}
			}

			$qty=0;
			if ($exactMatchId!=-1) {
				//set the quantity to be the quantity of the exact match id
				$query="SELECT quantity FROM InWishlist WHERE customid='".$exactMatchId."'";
				$qty= $mysqli->query($query);
				$qty= $qty->fetch_row();
				$qty=$qty[0];
			}

			if ($qty>0) { //this exact piece is already in the database for this user for this wishlist
				//instead of adding a new item, just update the quantity
				$qty++;
				$query = "UPDATE InWishlist SET quantity='".$qty."' WHERE customid= '" . $exactMatchId . "'"; 
				$result2 = $mysqli->query($query);	
				if($result2){
					$message = "Successfully added to wishlist: the item already exists, so the quantity increased by one";
					$customid=$exactMatchId;
					$keepGoing=true;
					//print($message);
				}
			} else { //this piece is not in the database yet for this user
				//ADD SQL TO CREATE CUSTOM ID, THEN ADD TO WISHLIST.	
				$query="INSERT INTO CustomPieces (modelno, categoryid, typeid, finishid, materialid, shapeid, length, width, height) values ('" . $modelno . "', '". $modelData['categoryid'] . "','" . $modelData['typeid'] .  "', '" . $modelData['finishid'] .  "', '" . $modelData['materialid'] .  "', '" . $modelData['shapeid'] .  "', '" . $modelData['length'] .  "', '" . $modelData['width'] .  "', '" . $modelData['height'] . "');";
				$result = $mysqli->query($query);
				if($result){							
					$query = "SELECT MAX(customid) as customid FROM CustomPieces WHERE modelno = '" . $modelno .  "';"; 
					$result2 = $mysqli->query($query);
					if($result2->num_rows != 0){
						$ans = $result2->fetch_assoc();
						$maxid = $ans['customid'];
						if(isset($maxid)){

							$query = "INSERT INTO InWishlist (wishlistid, customid) values ('" . $wishlistid . "', '" . $maxid . "');"; 
							$result2 = $mysqli->query($query);
							if($result2){
								$message = "Successfully added to wishlist";
								$customid=$maxid;
								$keepGoing=true;
								//print($message);
							}
						}
					}
				}
			}
		}
	}
}

	
//if GET(customid) isset and POST(anychanges) isset
if ($keepGoing && isset($_POST['submit'])) {
	if ($_POST['customid']==$customid){
		//process the change of that customid. 
		
		//first check to see if all the submitted values actually exist in the database
		$isLegit=0;
		$query=("SELECT * FROM ShapeTypes WHERE shapeid='".$_POST['shape']."'");
		$result= $mysqli->query($query);
		$isLegit+=$result->num_rows;
		
		$query=("SELECT * FROM MaterialTypes WHERE materialid='".$_POST['material']."'");
		$result= $mysqli->query($query);
		$isLegit+=$result->num_rows;
		
		$query=("SELECT * FROM FinishTypes WHERE finishid='".$_POST['finish']."'");
		$result= $mysqli->query($query);
		$isLegit+=$result->num_rows;
		
		//check if length, width, height are legit
		
		if ($isLegit==3){ //its legit (should be 6)
			$query=("UPDATE CustomPieces SET finishid=?,shapeid=?,materialid=?,length=?,width=?,height=? WHERE customid = ?");
			$stmt= $mysqli->stmt_init();
			if ($stmt->prepare($query)){
				$stmt->bind_param('iiiiiii',$_POST['finish'],$_POST['shape'],$_POST['material'],$_POST['length'],$_POST['width'],$_POST['height'],$_POST['customid']);
				$stmt->execute();
			}
			if($stmt->affected_rows>0){
				$message=$message."Custom piece updated successfully";
			} else {
				$message=$message."Custom piece update failed";
			}

		} else {
			$message=$message." There was an error processing the item you are trying to edit. ";
		}
	} else {
		$message=$message." There was an error processing the item you are trying to edit. ";
	}
}

//if GET(customid) isset and POST(reset) isset
if ($keepGoing && isset($_POST['reset'])) {
	if ($_POST['customid']==$customid){
		//reset the custom piece to the default values of the piece
	
		$query=("SELECT modelno FROM CustomPieces WHERE customid='".$_POST['customid']."'");
		$result= $mysqli->query($query);
		$modelno=$result->fetch_row();
		$modelno=$modelno[0];
		
		$query=("SELECT * FROM Pieces WHERE modelno='".$modelno."'");
		$result= $mysqli->query($query);
		$pieceData=$result->fetch_assoc();
		

		$query=("UPDATE CustomPieces SET finishid=?,shapeid=?,materialid=?,length=?,width=?,height=? WHERE customid = ?");
		$stmt= $mysqli->stmt_init();
		if ($stmt->prepare($query)){
			$stmt->bind_param('iiiiiii',$pieceData['finishid'],$pieceData['shapeid'],$pieceData['materialid'],$pieceData['length'],$pieceData['width'],$pieceData['height'],$_POST['customid']);
			$stmt->execute();
		}
		if($stmt->affected_rows>0){
			$message=$message."Custom piece reset successfully";
		} else {
			$message=$message."Custom piece reset failed";
		}
	} else {
		$message=$message." There was an error reseting the item you are trying to edit. ";
	}
}


	$page= "Edit Item";
	include ('includes/header.php');	
	include('includes/menubar.php');
?>
<div class="body_content">
	<h3>Edit Item Details:</h3>
<?php echo $message; 

	//if customid is set --> keepGoing
	//list all the details of that item (within inputs of a form)
	//allow the user to make changes to the inputs and submit the form
		//use dropdown menus where ever possible
	if ($keepGoing) {
		?>	<div class="wishlist-form"> <?php
		$query="SELECT * FROM CustomPieces WHERE customid='".$customid."'";
		$result = $mysqli->query($query);
		$custom=$result->fetch_assoc();
		
		$query="SELECT pname,description,photourl FROM Pieces WHERE modelno= '".$custom['modelno']."'";
		$result = $mysqli->query($query);
		$original=$result->fetch_assoc();
		$url = explode("/", $original['photourl']);
		
		//Part A (Partaaaaaaay... Party?)
		print("<form method=\"post\" action=\"edititem.php?customid=".$customid."\"><fieldset><span class=\"item-header\"><h3>".$original['pname']."</h3></span>");
		print("<div class=\"\"><img src=\"furniturethumbs/".$url[1]."\"/></div>");
		print("<div class=\"\"><p class=\"center\">Decription<br/>".$original['description']."</p>Model No: ".$custom['modelno']);
		$temp=$mysqli->query("SELECT tname FROM Types WHERE typeid='" . $custom['typeid'] ."'");
		$temp=$temp->fetch_row();
		print("<br/>\t\tItem: " . $temp[0]);
		
		$temp=$mysqli->query("SELECT cname FROM CategoryTypes WHERE categoryid='" . $custom['categoryid'] ."'");
		$temp=$temp->fetch_row();
		print("<br/>\t\tCategory: " . $temp[0]);	
		print("<br/><br/></div>");		
		
		//Part B
		print("<div>");
		print("Length: <input type=\"text\" name=\"length\" value=\"".$custom['length']."\" size=\"3\" /><br/> ");
		print("Width: <input type=\"text\" name=\"width\" value=\"".$custom['width']."\" size=\"3\" /><br/> ");
		print("Height: <input type=\"text\" name=\"height\" value=\"".$custom['height']."\" size=\"3\" />");
		print("</div>");
		
		//Part C 
		$result=$mysqli->query("SELECT * FROM FinishTypes ORDER BY fname");
		print("<br/>Finish: \n<select name=\"finish\">");
		while ($item= $result->fetch_row()) {
			if ($custom['finishid'] == $item[0]) {
				print("<option value=\"".$item[0]."\" selected>".$item[1]."</option>");
			} else {
				print("<option value=\"".$item[0]."\">".$item[1]."</option>");
			}
		}
		print("\n</select>");

		$result=$mysqli->query("SELECT * FROM MaterialTypes ORDER BY mname");
		print("<br/>Material: \n<select name=\"material\">");
		while ($item= $result->fetch_row()) {
			if ($custom['materialid'] == $item[0]) {
				print("<option value=\"".$item[0]."\" selected>".$item[1]."</option>");
			} else {
				print("<option value=\"".$item[0]."\">".$item[1]."</option>");
			}
		}
		print("\n</select>");

		$result=$mysqli->query("SELECT * FROM ShapeTypes ORDER BY sname");
		print("<br/>Shape: \n<select name=\"shape\">");
		while ($item= $result->fetch_row()) {
			if ($custom['shapeid'] == $item[0]) {
				print("<option value=\"".$item[0]."\" selected>".$item[1]."</option>");
			} else {
				print("<option value=\"".$item[0]."\">".$item[1]."</option>");
			}
		}
		print("\n</select>");
		
		print("<input type=\"hidden\" name=\"customid\" value=\"".$custom['customid']."\"/><br/>");
		print("<br/><input type=\"submit\" name=\"submit\" value=\"Update Details\" />");
		print("<input type=\"submit\" name=\"reset\" value=\"Reset to Default Values\" />");
		print("</fieldset></form>");
		print("<br/>\n<a href=\"wishlist.php?id=".$currentWishlistId."\">Back to Wishlist</a>");
		?>	 </div>	<?php
	}
	$mysqli->close();
?>
</div>
<?php
include ('includes/footer.php');
?>
</body>
</html>